package concursos.daos;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import concursos.modelos.Concurso;
import concursos.modelos.Disciplina;

public class DisciplinaDAO {

	private EntityManager manager;

	public DisciplinaDAO(EntityManager manager) {
		this.manager = manager;
	}

	public void adicionarDisciplina(Disciplina disciplina) {
		if (disciplina.getId() == 0)
			this.manager.persist(disciplina);
		else
		{
			System.out.println("Atualizando disciplina...");
			Disciplina temp = this.manager.find(Disciplina.class, disciplina.getId());
			temp.setNome(disciplina.getNome());
			this.manager.merge(disciplina);
		}
	}

	public void atualizarDisciplina(Disciplina disciplina) {
		this.manager.persist(disciplina);
	}

	public void excluirDisciplina(Disciplina disciplina) {
		this.manager.remove(manager.getReference(Disciplina.class,
				disciplina.getId()));
	}

	public List<Disciplina> listarDisciplina(int usuario) {
		TypedQuery<Disciplina> query = this.manager.createQuery(
				"select x from Disciplina x.concurso.usuario.id = :usuario", Disciplina.class);
		query.setParameter("usuario", usuario);
		return query.getResultList();
	}

	public Disciplina buscaPorId(int id) {
		Disciplina disciplina = this.manager.find(Disciplina.class, id);
		return disciplina;
	}

	public List<Disciplina> buscarPorConcurso(int id) {
		TypedQuery<Disciplina> query = this.manager.createQuery(
				"select x from Disciplina x where x.concurso.id = :id",
				Disciplina.class);

		query.setParameter("id", id);

		return query.getResultList();
	}

}
